import type { CartItemProps, ProductProps } from '@/types/storeType'
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useCartStore = defineStore(
  'cart',
  () => {
    const items = ref<CartItemProps[]>([])

    const totalCount = computed(() => {
      return items.value.reduce((acc, item) => acc + item.quantity, 0)
    })

    const totalPrice = computed(() => {
      return items.value.reduce((acc, item) => acc + item.price * item.quantity, 0)
    })

    const isEmpty = computed(() => {
      return items.value.length === 0
    })

    function addItem(item: ProductProps, quantity: number = 1) {
      const existingItem = items.value.find((i) => i.id === item.id)
      if (existingItem) {
        existingItem.quantity += quantity
      } else {
        items.value.push({
          ...item,
          quantity,
        })
      }
    }

    function removeItem(productId: number) {
      const index = items.value.findIndex((item) => item.id === productId)
      if (index !== -1) {
        items.value.splice(index, 1)
      }
    }

    function updateQuantity(productId: number, quantity: number) {
      const item = items.value.find((item) => item.id === productId)
      if (item) {
        if (quantity > 0) {
          item.quantity = quantity
        } else {
          removeItem(productId)
        }
      }
    }

    function clearCart() {
      items.value = []
    }

    return {
      items,
      isEmpty,
      totalCount,
      totalPrice,
      addItem,
      removeItem,
      updateQuantity,
      clearCart,
    }
  },
  { persist: true },
)
